//导入 antd-mobile的组件
import { NavBar, DatePicker } from "antd-mobile";
// 导入dayjs模块
import dayjs from "dayjs";
// 导入Redux中的useSelector
import { useSelector } from "react-redux";
// 导入lodash的groupBy方法
import _ from "lodash";
// 导入必要React模块
import "./index.scss";
import { useState, useMemo, useEffect } from "react";
// 导入声明类型
import type { RootState } from "../../store";
// 导入账单数据类型
import type { BillType } from "../../types/billType";
// 导入DailyBill组件
import DailyBill from "./components/DailyBill/index";

// 月度收支页面
const Month = () => {
  // 时间选择器是否显示
  const [dataVisible, setDataVisible] = useState(false);
  // 控制时间显示
  const [currentDate, setCurrentDate] = useState(() => {
    return dayjs(new Date()).format("YYYY-MM");
  });
  // 选中的日期数据
  const [currentMonthList, setCurrentMonthList] = useState<BillType[]>([]);

  // 从redux获取数据
  const billData = useSelector((state: RootState) => state.bill.billData);

  // 时间选择器确认回调
  const onDatePickerConfirm = (val: Date) => {
    setDataVisible(false);
    const formatDate = dayjs(val).format("YYYY-MM");
    // 处理时间选择器确认回调
    setCurrentDate(formatDate);
    setCurrentMonthList(monthGroup[formatDate] || []);
  };

  // 使用useMemo，相当于Vue中的computed属性
  // 按月进行分组
  const monthGroup = useMemo(() => {
    // 使用lodash模块用于计算按日期分组后的数据
    return _.groupBy(billData, (item: BillType) =>
      dayjs(item.date).format("YYYY-MM")
    );
  }, [billData]);

  // 按日进行分组
  const dayGroup = useMemo(() => {
    // 按日进行的分组
    const groupDate = _.groupBy(currentMonthList, (item: BillType) =>
      dayjs(item.date).format("YYYY-MM-DD")
    );
    // 按日进行分组后的日期键值
    const groupDateKeys = Object.keys(groupDate);
    return { groupDate, groupDateKeys };
  }, [currentMonthList]);

  // 计算支出、收入、结余
  const montyResult = useMemo(() => {
    const pay = currentMonthList
      .filter((item) => item.type === "pay")
      .reduce((a, c) => a + c.money, 0);
    const income = currentMonthList
      .filter((item) => item.type === "income")
      .reduce((a, c) => a + c.money, 0);
    return {
      pay,
      income,
      total: pay + income,
    };
  }, [currentMonthList]);

  // 页面加载时，显示当前月的数据
  useEffect(() => {
    const nowDate = dayjs().format("YYYY-MM");
    setCurrentMonthList(monthGroup[nowDate] || []);
  }, [monthGroup]);
  return (
    <>
      <div className="monthlyBill">
        <NavBar className="nav" backArrow={false}>
          月度收支
        </NavBar>
        <div className="content">
          <div className="header">
            {/* 时间切换区域 */}
            <div className="date" onClick={() => setDataVisible(true)}>
              <span className="text">{currentDate + ""}月账单</span>
              <span className={dataVisible ? "arrow expand" : "arrow"}></span>
            </div>
            {/* 统计区域 */}
            <div className="twoLineOverview">
              <div className="item">
                <span className="money"> {montyResult?.pay.toFixed(2)}</span>
                <span className="type">支出</span>
              </div>
              <div className="item">
                <span className="money"> {montyResult?.income.toFixed(2)}</span>
                <span className="type">收入</span>
              </div>
              <div className="item">
                <span className="money"> {montyResult?.total.toFixed(2)}</span>
                <span className="type">结余</span>
              </div>
            </div>
            {/* 时间选择器 */}
            <DatePicker
              className="kaDate"
              title="记账日期"
              precision="month"
              visible={dataVisible}
              max={new Date()}
              onCancel={() => setDataVisible(false)}
              onConfirm={(val) => onDatePickerConfirm(val)}
            />
          </div>
          {dayGroup.groupDateKeys.map((item) => {
            return (
              <DailyBill
                key={item}
                billDate={item}
                billList={dayGroup.groupDate[item]}
              />
            );
          })}
        </div>
      </div>
    </>
  );
};

export default Month;
